/*
 * RigidBody that is used for player controls
 */
package com.cmp.player.controls;

import com.jme3.bullet.collision.PhysicsRayTestResult;
import com.jme3.bullet.collision.shapes.CapsuleCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;
import java.util.List;

/**
 *
 * @author pfanne
 */
public class CharacterRigidBodyControl extends RigidBodyControl{
    private boolean onGround;
    private boolean checkedOnGround;
    private float radius, height;
    public CharacterRigidBodyControl(float radius, float height, float mass) {
        super(new CapsuleCollisionShape(radius, Math.max(0.f,height - 2 * radius)), mass);
        setAngularFactor(0.f);
        setFriction(0.f);
        onGround = false;
        checkedOnGround = false;
        this.radius = radius;
        this.height = Math.max(0.f,height - 2 * radius) + 2 * radius;
    }
    
    protected void checkOnGround() {
        Vector3f from = this.getPhysicsLocation();
        Vector3f to = from.subtract(new Vector3f(0, height / 2.f +0.01f,0));
        List<PhysicsRayTestResult> results = getPhysicsSpace().rayTest(from,to);
        for (PhysicsRayTestResult physicsRayTestResult : results) {
            if (!physicsRayTestResult.getCollisionObject().equals(this)) {
                onGround = true;
                return;
            }
        }
        onGround = false;
    }
    @Override
    public void update(float tpf) {
        checkedOnGround = false;
        super.update(tpf);
    }

    public boolean isOnGround() {
        if(!checkedOnGround) {
            checkOnGround();
            checkedOnGround = true;
        }
        return onGround;
    }
    
    public Spatial getSpatial() {
        return spatial;
    }
}
